<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      label-position="right"
    >
      <!-- <el-form-item label="选择机构" prop="organization">

        <el-input v-model="formData.organization" placeholder="请选择机构" />
      </el-form-item> -->
      <el-form-item label="选择机构" prop="orgId">
        <el-select
          v-model="formData.orgId"
          placeholder="请选择机构"
          clearable
          style="width: 160px"
          @change="changeDeptTree()"
        >
          <el-option
            v-for="item in orgTree"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="t('page_sys.dept.labelSjbm')"
        prop="parentId"
        :render-after-expand="false"
      >
        <el-tree-select
          v-model="formData.parentId"
          :data="deptTree"
          :placeholder="t('page_sys.dept.placeholderSjbm')"
          check-strictly="true"
        />
      </el-form-item>
      <div class="flex">
        <el-form-item :label="t('page_sys.dept.labelBmmc')" prop="name" class="flex-1">
          <el-input v-model="formData.name" :placeholder="t('page_sys.dept.placeholderBmmc')" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="sort" class="flex-1 ml-2">
          <el-input-number v-model="formData.sort" placeholder="请输入显示顺序" class="flex-1" />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="负责人" prop="leaderUserId" class="flex-1">
          <el-select v-model="formData.leaderUserId">
            <el-option
              v-for="item in personList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" class="flex-1 ml-2">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="邮箱" prop="email" class="flex-1">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="部门状态" prop="status" class="flex-1 ml-2">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="科室编码" prop="code" class="flex-1">
          <el-input v-model="formData.code" placeholder="科室编码" />
        </el-form-item>
        <el-form-item label="使用范围" prop="scope" class="flex-1">
          <el-select multiple v-model="formData.scope">
            <el-option
              v-for="item in scopeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          /></el-select>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('action.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm">{{ t('action.save') }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { CommonStatusEnum } from '@/utils/constants'
import { FormRules } from 'element-plus'
import * as qualifiApi from '@/api/qualification'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  organization: undefined,
  id: undefined,
  // title: '',
  parentId: undefined,
  name: undefined,
  email: undefined,
  phone: undefined,
  leaderUserId: undefined,
  code: undefined,
  scope: undefined,
  orgId: undefined,
  sort: 0,
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: t('page_sys.dept.tipBmmcBnwk'), trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'change' }],
  code: [{ required: true, message: '科室编码不能为空', trigger: 'blur' }],
  scope: [{ required: true, message: '使用范围不能为空', trigger: 'blur' }],
  orgId: [{ required: true, message: '所属机构不能为空', trigger: 'blur' }]
  // sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  // email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  // phone: [
  //   { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  // ],
  // status: [{ required: true, message: '部门状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const personList = ref()
const orgTree = ref([])
const scopeList = ref([
  { label: '门诊', value: '0' },
  { label: '住院', value: '1' },
  { label: '急诊', value: '2' },
  { label: '全院', value: '3' }
])
/** 查询白名单列表 */
const getUserList = async () => {
  const data = await qualifiApi.searchAllMedicalUsers()
  let list: any = []
  data.MedicalUserList.map((v) => {
    list.push({
      name: v.name,
      id: v.id
    })
  })
  personList.value = list
}
const changeDeptTree = () => {
  formData.value.parentId = undefined
  getTree(formData.value.orgId)
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + '科室'
  formType.value = type
  resetForm()
  getUserList()
  getOrgTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await DeptApi.getDept(id)
      if (type == 'create') {
        formData.value.orgId = data.dept.orgId
        formData.value.parentId = data.dept.parentId
        // 获得部门树
        await getTree(data.dept.orgId)
      } else {
        data.dept.scope = JSON.parse(data.dept.scope)
        formData.value = data.dept
        // 获得部门树
        await getTree(formData.value.orgId)
      }
    } finally {
      formLoading.value = false
    }
  }
  // 获得用户列表
  userList.value = await UserApi.getSimpleUserList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeptApi.DeptVO
    if (formType.value === 'create') {
      await DeptApi.createDept(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeptApi.updateDept(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    // title: '',
    parentId: undefined,
    name: undefined,
    sort: 0,
    leaderUserId: undefined,
    phone: undefined,
    email: undefined,
    organization: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}

const getGroupListTrees = (data: any) => {
  if (Array.isArray(data)) {
    return data.map((item) => getGroupListTrees(item))
  } else if (typeof data === 'object' && data !== null) {
    const result: any = {}
    for (let key in data) {
      if (key === 'name') {
        result.label = data[key]
      } else if (key === 'id') {
        result.value = data[key]
      } else {
        result[key] = getGroupListTrees(data[key])
      }
    }
    return result
  } else {
    return data
  }
}
/** 获得机构树 */
const getOrgTree = async () => {
  orgTree.value = []
  const data = await DeptApi.getOrgTree()
  orgTree.value = getGroupListTrees(data.tree)
}

/** 获得部门树 */
const getTree = async (orgId?: any) => {
  deptTree.value = []
  const data = await DeptApi.getDeptTree({ orgId })
  deptTree.value = getGroupListTrees(data.tree)
}
</script>
